

$(document).ready(function() {
	datatablePlugins();
	datatableConfig();
	tmp();
});

	

/**
 * Add extra funcionality to datatable plugin
 */
function datatablePlugins() {
	
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
	{
	    if ( typeof sNewSource != 'undefined' && sNewSource != null )
	    {
	        oSettings.sAjaxSource = sNewSource;
	    }
	    this.oApi._fnProcessingDisplay( oSettings, true );
	    var that = this;
	    var iStart = oSettings._iDisplayStart;
	    var aData = [];
	 
	    this.oApi._fnServerParams( oSettings, aData );
	     
	    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
	        /* Clear the old information from the table */
	        that.oApi._fnClearTable( oSettings );
	         
	        /* Got the data - add it to the table */
	        var aData =  (oSettings.sAjaxDataProp !== "") ?
	            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
	         
	        for ( var i=0 ; i<aData.length ; i++ )
	        {
	            that.oApi._fnAddData( oSettings, aData[i] );
	        }
	         
	        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	        that.fnDraw();
	         
	        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
	        {
	            oSettings._iDisplayStart = iStart;
	            that.fnDraw( false );
	        }
	         
	        that.oApi._fnProcessingDisplay( oSettings, false );
	         
	        /* Callback user function - for event handlers etc */
	        if ( typeof fnCallback == 'function' && fnCallback != null )
	        {
	            fnCallback( oSettings );
	        }
	    }, oSettings );
	};
}


function datatableConfig() {
	
	var oTable = $('#classesTable');
	
	var classSchedulesDiv = $('#classSchedulesDiv');
	
	var clientsDiv = $('#clientsDiv');
	
	var tableStructure = clientsDiv.html();
	
	clientsDiv.empty();
	
	var serverRequest = ajaxUrl + '/readClassesAction';
	
	var tableProperties = {		
			
		'sAjaxSource': 		serverRequest,	
		'fnServerParams':	function(aoData) {

			// POST values 2 send
			aoData.push({
				"name":		"field01",
				"value":	'val01'
			});
			aoData.push({
				"name":		"field02",
				"value":	'val02'
			});
			aoData.push({
				"name":		"field03",
				"value":	'val03'
			});
			aoData.push({
				"name":		"field04",
				"value":	'val04'
			});
		},
		'sServerMethod':	'POST',
		'sAjaxDataProp': 	'data',
		"aoColumns": [
  			{"mDataProp":"offerName"},
  			{"mDataProp":"classes"},
  			{"mDataProp":"start"},
  			//{"mDataProp":"end"},
  			{"mDataProp":"part"},
  			{"mDataProp":"spots"}
  			//{"mDataProp":"company"}
		  ],
		  'oLanguage': {
			'sInfo':		'registo _START_ até ao _END_ de _TOTAL_',
			'sZeroRecords': 'Não existem registos',
			'sSearch':		'Procurar',
			'sLengthMenu':	'Mostrar <select>' +
		        '<option value="10">10</option>'+
		        '<option value="15">15</option>'+
		        '<option value="20">20</option>'+
		        //'<option value="50">50</option>'+
		        //'<option value="-1">Todas</option>'+
		        '</select> Aulas'
			},
		'aaSorting':[[2,'asc']],	// or 'asc'
		'bJQueryUI':		true,	// enable jqueryUI Themes
		'bPaginate':		true,
		'bSort':			true,
		'bInfo':			true,
		'bAutoWidth':		true,
		'bProcessing': 		false,	
		'bServerSide': 		false	// use server side processing
	};

	oTable.dataTable(tableProperties);
	
	// TABLE CLICK
	oTable.find('tbody tr').live('click', function() {
		
		if ( $(this).hasClass('row_selected') ) { 
			
			classSchedulesDiv.empty();
			clientsDiv.empty();
			
            $(this).removeClass('row_selected'); 
            
            return;
		}
		else { // row isnt selected
			
			classSchedulesDiv.empty();
			clientsDiv.empty();
			
	       	oTable.$('tr.row_selected').removeClass('row_selected');
	       	
	        $(this).addClass('row_selected');
	        
	        var classData = oTable.fnGetData(this);
			
	        var dataRequest = {
	        	classID: classData.classId	
	        };
	        
	        $.ajax({
				url: 		window.ajaxUrl + '/getClassInfo',
				async: 		true, 
				data: 		{ data: dataRequest},
				type: 		'POST',
				dataType: 	'json',
				success: 	function(classInfo) {
					
					// display schedules
					$.each(classInfo.schedules, function(key, value) {
						var cal_container = '<div class="cal-container"><div class="cal-class-label inside-cal-container"><p>Aula '+ (key+1) + ':</p></div> <div class="cal-data-container inside-cal-container"><div class="cal-date-label"><p>Inicio:</p></div><div class="cal-date"><p>' + classInfo.schedules[key].start +'</p></div><div class="cal-date-label"><p>Fim:</p></div><div class="cal-date"><p>' + classInfo.schedules[key].end + '</div></p></div></div>';
						$(cal_container).appendTo(classSchedulesDiv);
					});
					
					var noClientTags = '<h2><span>Esta aula ainda não contem participantes</span></h2> ';
					
					if ($.isEmptyObject(classInfo.clients)) {
						
						$(noClientTags).appendTo(clientsDiv);
					}
					else {
						
						$(tableStructure).appendTo(clientsDiv);
						
						var tbody = $('#clientTable').find('tbody');
						
						var hotelPercentage = null;
						
						var payedInHotel = null;
						
						var payedInHotelLabel = '';
						
						var toReceive = 0;
						
						$.each(classInfo.clients, function(key, value) {
							
							if (classInfo.clients[key].hotelPayment) {
								
								hotelPercentage = classInfo.clients[key].hotelPayment/100;
							
								payedInHotel = classInfo.clients[key].total*hotelPercentage;
								
								payedInHotelLabel = payedInHotel + ' € ('+ classInfo.clients[key].hotelPayment +'%)</td> ';
								
								toReceive = classInfo.clients[key].total-payedInHotel;
							}
							else {
								
								payedInHotelLabel = '...';
								
								toReceive = classInfo.clients[key].total;
							}
							
							var clientRow = '' + 
							'<tr>' +
								'<td class="align-center">' + (key+1) + '</td>' +
								'<td><a href="#" class="clientLink" data-arrayIndex="' + key + '">' + classInfo.clients[key].clientName + '</a></td>' +
								'<td>' + classInfo.clients[key].reservationDate + '</td>' + 
								'<td>' + classInfo.clients[key].total + ' €</td>' + 
								'<td>' + payedInHotelLabel + 
								'<td>' + toReceive + ' €</td> ' + 
								'<td>' + classInfo.clients[key].entityName + '</td> ' + 
							'</tr>';
							
							$(clientRow).appendTo(tbody);
						});
						
						clientLinkEvents(classInfo.clients);
					}
					
					return;
				}
			});
		}
	});
}


function tmp() {
	
}



/**
 * Function called when a list of clients is displayed.
 * handle events of those links here ...
 * @param clients - clients with reservation in the selected offer
 */
function clientLinkEvents(clients) {
	
	$('.clientLink').click(function(event) {
		
		event.preventDefault();
		
		var client = clients[$(this).attr('data-arrayIndex')];
		
		var clientInfo = $('#clientInfo');
		
		clientInfo.find('#clientName').html(client.clientName);
		clientInfo.find('#clientAddress').html(client.clientAddress);
		clientInfo.find('#clientPhone').html(client.clientPhone);
		clientInfo.find('#clientEmail').html(client.clientEmail);
		clientInfo.find('#clientBirthday').html(client.clientBirthday);
		clientInfo.find('#clientSex').html(client.clientSex);
		clientInfo.find('#clientHeight').html(client.clientHeight);
		clientInfo.find('#clientWeight').html(client.clientWeight);
		clientInfo.find('#clientNationality').html(client.clientNationality);
		
		var opt = {
			width:		600,
			height:		550,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				}
			}
		};
		
		clientInfo.dialog(opt);
	});
}

